package com.qf.micro_msg;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AppRunning implements CommandLineRunner {

    private EventLoopGroup master = new NioEventLoopGroup();
    private EventLoopGroup slave = new NioEventLoopGroup();

    @Value("${server.port}")
    private int ports;

    @Autowired
    private List<ChannelHandler> channelHandlers;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("消息中心运行....");

        System.out.println("ChannelHandler的顺序：");
        channelHandlers.stream().forEach(System.out::println);

        //运行Netty服务端
        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(master, slave)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        //添加处理器
                        ChannelPipeline pipeline = ch.pipeline();

                        //对Http的支持
                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new HttpObjectAggregator(1024 * 10));
                        //对WebSocket的支持
                        pipeline.addLast(new WebSocketServerProtocolHandler("/"));
                        //心跳过期超时的处理
                        pipeline.addLast(new ReadTimeoutHandler(30, TimeUnit.SECONDS));
                        //自定义消息的处理（提醒消息，注册消息，心跳消息，单聊，群聊消息....）
                        for (ChannelHandler channelHandler : channelHandlers) {
                            pipeline.addLast(channelHandler);
                        }
//                        pipeline.addLast(channelHandlers.toArray(new ChannelHandler[0]));

                    }
                });

        //运行Netty服务器
        ChannelFuture future = bootstrap.bind(ports);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("消息中心启动成功，端口号为：" + ports);
                }
            }
        });
    }
}
